package no.ntnu.idi.deid.documentunits;

import java.util.Iterator;

public class TokenIterator implements Iterator<Token> {

	private Document mDocument;
	private int mSectionPointer;
	private int mSentencePointer;
	private int mTokenPointer;

	public TokenIterator(Document document) {
		if(document == null) {
			throw new IllegalArgumentException("Cannot iterate over null element");
		}
		mDocument = document;
		mSectionPointer = 0;
		mSentencePointer = 0;
		mTokenPointer = -1;
	}
	
	@Override
	public Token next() {
	    Section sec = mDocument.get(mSectionPointer);
	    Sentence sentence = sec.get(mSentencePointer);
	    mTokenPointer++;
	    
	    if(mTokenPointer >= sentence.size()) {
	    	mTokenPointer = 0;
	    	mSentencePointer++;
	    }
	    
	    if(mSentencePointer >= sec.size()) {
	    	mSentencePointer = 0;
	    	mSectionPointer++;
	    }
	    
	    sec = mDocument.get(mSectionPointer);
	    sentence = sec.get(mSentencePointer);
	    Token token = sentence.get(mTokenPointer);
	    return token;
	}
	

	@Override
	public boolean hasNext() {
		if(mDocument.size() == 0) {
			return false;
		}
	    Section sec = mDocument.get(mSectionPointer);
	    Sentence sentence = sec.get(mSentencePointer);
	    int tokenPointer = mTokenPointer;
	    int sentencePointer = mSentencePointer;
	    int sectionPointer = mSectionPointer;
	    tokenPointer++;
	    
	    if(tokenPointer >= sentence.size()) {
	    	sentencePointer++;
	    }
	    else {
	    	return true;
	    }
	    
	    if(sentencePointer >= sec.size()) {
	    	sectionPointer++;
	    }
	    else {
	    	return true;
	    }
	    if(sectionPointer >= mDocument.size()) {
	    	return false;
	    }
	    else {
	    	return true;
	    }
	}

	/**
	 * Not supported
	 */
	@Override
	public void remove() {
		throw new UnsupportedOperationException("This feature is not supported");
		
	}	
}
